<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    :close-on-click-modal="false"
    @close="closeRoleDialog"
    @open="openDiloag"
  >
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="roleIds" v-loading="isLoading">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="assignRole">确定</el-button>
      <el-button size="small" @click="closeRoleDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleListApi } from '@/api/setting'
import { getUserAvatarApi } from '@/api/user'
import { assignRoleApi } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      roleIds: [],
      roleList: [],
      isLoading: false
    }
  },
  methods: {
    async assignRole() {
      await assignRoleApi(this.userId, this.roleIds)
      this.$message.success('恭喜！分配角色成功')
      this.closeRoleDialog()
    },
    async openDiloag() {
      this.isLoading = true
      await this.getRoleList()
      await this.getUserRole()
      this.isLoading = false
    },
    /**
     * 获取所有角色列表
     */
    async getRoleList() {
      const { data: { rows }} = await getRoleListApi(1, 99999)
      this.roleList = rows
    },
    /**
     * 获取用户原本的角色信息
     */
    async getUserRole() {
      const { data: { roleIds }} = await getUserAvatarApi(this.userId)
      // 当roleIds为null的时候 默认让他是一个[]
      this.roleIds = roleIds || []
    },
    /**
     * 关闭弹框
     */
    closeRoleDialog() {
      this.$emit('update:showRoleDialog', false)
    }
  }
}
</script>
